package com.lqs.blog.service.Impl;

import com.alibaba.fastjson.JSON;
import com.lqs.blog.pojo.SysUser;
import com.lqs.blog.service.LoginService;
import com.lqs.blog.service.SysUserService;
import com.lqs.blog.utils.JWTUtils;
import com.lqs.blog.vo.ErrorCode;
import com.lqs.blog.vo.Result;
import com.lqs.blog.vo.param.LoginParams;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    RedisTemplate<String, String> redisTemplate;
    private static final String salt = "!@#";//加密盐

    @Override
    public Result login(LoginParams loginParams) {
            /*1.检查参数是否合法
        2.根据用户和密码去user表中查询是否存在
        3.如果不存在登录失败
        4.如果存在，使用jwt生成token 返回给前端
        5.token放入redis当中，token: 用户信息 设置过期时间
        （登录认证的时候 先认证token是否合法，去redis认证是否存在）
         *
         */
        String account = loginParams.getAccount();
        String password = loginParams.getPassword();
        if (StringUtils.isBlank(account) || StringUtils.isBlank(password)) {
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        }

        password = DigestUtils.md5Hex(password + salt);
        SysUser user = sysUserService.getUserByAccountAndPassword(account, password);
        if (user == null) {
            return Result.fail(ErrorCode.ACCOUNT_PWD_NOT_EXIST.getCode(), ErrorCode.ACCOUNT_PWD_NOT_EXIST.getMsg());
        }

        //得到token
        String token = JWTUtils.createToken(user.getId());
        //将user转为String类型 过期时间一天
        redisTemplate.opsForValue().set("TOKEN_" + token, JSON.toJSONString(user), 1, TimeUnit.DAYS);
        return Result.success(token);
    }

    @Override
    public SysUser checkToken(String token) {
        if (StringUtils.isBlank(token)) {
            return null;
        }
        Map<String, Object> map = JWTUtils.checkToken(token);
        if (map == null) {
            return null;
        }
        //判断在redis中是否存在
        String userJson = redisTemplate.opsForValue().get("TOKEN_" + token);
        if (StringUtils.isBlank(userJson)) {
            return null;
        }
        //将userJson解析为SysUser对象
        SysUser user = JSON.parseObject(userJson, SysUser.class);
        return user;
    }

    @Override
    public Result loginout(String token) {
        //删除redis中存放的token
        redisTemplate.delete("TOKEN_" + token);
        return Result.success(null);
    }
}
